package com.tianji.learning.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.tianji.common.utils.BeanUtils;
import com.tianji.learning.domain.po.PointsBoardSeason;
import com.tianji.learning.domain.vo.PointsBoardSeasonVO;
import com.tianji.learning.mapper.PointsBoardSeasonMapper;
import com.tianji.learning.service.IPointsBoardSeasonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author huanmo
 * @since 2025-09-24
 */
@Service
public class PointsBoardSeasonServiceImpl extends ServiceImpl<PointsBoardSeasonMapper, PointsBoardSeason> implements IPointsBoardSeasonService {

    @Override
    public List<PointsBoardSeasonVO> getSeasons() {
        LocalDateTime now = LocalDateTime.now();
        // 获取当前赛季
        Integer currentSeason = querySeasonByTime(now);
        // 查询数据
        List<PointsBoardSeason> list = lambdaQuery()
                .le(PointsBoardSeason::getId, currentSeason)
                .list();
        // 处理空结果
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list.stream()
                .map(season -> {
                    PointsBoardSeasonVO vo = new PointsBoardSeasonVO();
                    BeanUtils.copyProperties(season, vo);
                    return vo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public Integer querySeasonByTime(LocalDateTime time) {
        Optional<PointsBoardSeason> pointsBoardSeason = lambdaQuery()
                .le(PointsBoardSeason::getBeginTime, time)
                .ge(PointsBoardSeason::getEndTime, time)
                .oneOpt();
        return pointsBoardSeason.map(PointsBoardSeason::getId).orElse(null);
    }

    @Override
    public PointsBoardSeason queryBySeason(Integer season) {
        return lambdaQuery()
                .eq(PointsBoardSeason::getId, season)
                .one();
    }
}
